package service

import (
	"fmt"
	"rongyy/src/models"
	"strings"
)

type PaymentTrackService struct {
	d *models.PaymentTrackModel
}

func (ds *PaymentTrackService) Create(req *models.PaymentTrackModel) error {
	sm := &models.PaymentTrackModel{}
	err := sm.Create()
	if err != nil {
		return err
	}
	return nil
}

//func (ds *OrderTrackService) QueryTrackOrder(req *models.ReqTrack) ([]models.OrderTrackModel, int64, error) {
//	rm := &models.OrderTrackModel{}
//	data, total, err := rm.QueryTrackOrder(req)
//	if err != nil {
//		return nil, 0, err
//	}
//	return data, total, nil
//}

func (ds *PaymentTrackService) QueryErrorOrder(req *models.PaymentOrders) (*models.ErrorPaymentRespData, error) {
	order := &models.ErrorPaymentRespDataStuct{
		Info: nil,
		Msg:  "",
	}
	// 先查询系统内订单
	if strings.Contains(req.OrderSn, "R") {
		fmt.Println(1)
		// 查询订单是否成功
		reg, has, err := (&models.RegisterModel{}).FindByOrderSn(req.OrderSn)
		if err != nil {
			return nil, err
		}
		fmt.Println(2)
		if !has {
			order.Info = nil
			order.Msg = "订单信息不存在"
		} else {
			if reg.Status == "confirm" {
				order.Info = reg
				order.Msg = "订单状态正常"

			}
			if reg.Status != "confirm" {
				order.Info = reg
				order.Msg = "订单在his端未确认成功"
			}
		}

	}
	if strings.Contains(req.OrderSn, "P") {
		// 查询订单是否成功
		pm, has, err := (&models.PrescriptionModel{}).FindByOrderSn(req.OrderSn)
		if err != nil {
			return nil, err
		}
		if has && pm.Status == "confirm" && pm.PayStatus == "paid" {
			order.Info = pm
			order.Msg = "订单状态正常"
		} else {
			order.Info = pm
			order.Msg = "订单在his端未确认成功"
		}
	}

	// 银行端
	payment := &models.ErrorPaymentRespDataStuct{
		Info: nil,
		Msg:  "",
	}
	reqCcb := &models.PaymentReq{
		MerchantId: 7,
		OrderSn:    req.OrderSn,
	}
	// 第一步查询订单支付状态
	data, err := (&PaymentService{}).Query(reqCcb)

	if err != nil {
		return nil, err
	}
	//data.Data
	fmt.Println(data.Data.ReturnCode)
	if data.Data.ReturnCode != "000000" {
		payment.Info = nil
		payment.Msg = data.Data.ReturnMsg
	} else {
		if data.Data.TxInfo.List[0].OrderStatus == 4 {
			payment.Info = data.Data
			payment.Msg = "订单已退款" + data.Data.TxInfo.List[0].RefundMoney + "元"
		}
		if data.Data.TxInfo.List[0].OrderStatus == 1 {
			payment.Info = data.Data
			payment.Msg = "订单支付成功" + data.Data.TxInfo.List[0].PaymentMoney + "元"
		}
	}
	msg := ""
	if data.Data.ReturnCode == "000000" && order.Msg != "订单状态正常" {
		msg = "此订单可能是单边账"
	}

	final := &models.ErrorPaymentRespData{
		OrderInfo:   *order,
		PaymentInfo: *payment,
		Msg:         msg,
	}
	return final, nil
}
